package com.cc.openeye.dynamic.recommend

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import com.cc.openeye.constance.RequestUrlConst
import com.cc.openeye.dynamic.DynamicModel
import com.cc.openeye.dynamic.recommend.entity.LoadMoreStatus
import com.cc.openeye.dynamic.recommend.entity.dynamicResponse.DynamicResponse
import com.cc.openeye.dynamic.recommend.entity.dynamicResponse.Item

class RecommendViewModel {

    private val dynamicModel by lazy {
        DynamicModel.newInstance()
    }

    val dynamicResponse = mutableStateOf<DynamicResponse?>(null)

    val datas = mutableStateListOf<Item>()

    private val requestUrl = mutableStateOf(RequestUrlConst.DYNAMIC_URL)

    val loadMoreStatus = mutableStateOf(LoadMoreStatus.HaveMore)

    private var isLoading = false

    suspend fun requestDynamicData() {
        if (loadMoreStatus.value == LoadMoreStatus.NoMore) return
        if (isLoading) return
        isLoading = true
        val response = dynamicModel.requestDynamicData(requestUrl.value)
        isLoading = false
        if (response.success) {
            dynamicResponse.value = response.data
            datas.add(Item.createPreLoadItem())
            datas.addAll(response.data?.getDataList() ?: emptyList())
            requestUrl.value = response.data?.nextPageUrl ?: ""
            loadMoreStatus.value =
                if (requestUrl.value.isNotEmpty()) LoadMoreStatus.HaveMore else LoadMoreStatus.NoMore
        } else {
            loadMoreStatus.value = LoadMoreStatus.LoadErr
        }
    }

    companion object {
        fun newInstance() = RecommendViewModel()
    }
}